﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DTO;
using Business_Layer;
using System.Collections.Generic;

public partial class ViewCart : System.Web.UI.Page
{
    ShoppingCart Cart;
    List<HinhThuc> hinhThucs;
    string wsBankingURL = System.Configuration.ConfigurationManager.ConnectionStrings["BakingURL"].ToString();
    string wsBankingName = System.Configuration.ConfigurationManager.ConnectionStrings["BakingWSName"].ToString();

    string wsMovingURL = System.Configuration.ConfigurationManager.ConnectionStrings["MovingURL"].ToString();
    string wsMovingName = "Moving01Services";
    string movingSID;

    MovingWSProxy.Moving01ServicesSoapClient movingWS = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        string wsMethodName;
        object result;
        this.Cart = (ShoppingCart)Session["ShoppingCart"];

        wsMethodName = "LayDanhSachHinhThuc";
        result = MovingServiceProxy.CallWebService(wsMovingURL, wsMovingName, wsMethodName, new object[] { });
        hinhThucs = WebServiceInvoker.ConvertType<List<HinhThuc>>(result);

        if (!IsPostBack)
        {
            this.FillShoppingCart();

            // get Moving data
            try
            {
                dsHinhThucCBX.DataSource = hinhThucs;
                dsHinhThucCBX.DataValueField = "MaHinhThuc";
                dsHinhThucCBX.DataTextField = "MoTaHinhThuc";
                dsHinhThucCBX.DataBind();
                dsHinhThucCBX.SelectedIndex = dsHinhThucCBX.Items.Count > 1 ? 1 : -1;
                dsHinhThucCBX.SelectedIndex = dsHinhThucCBX.Items.Count > 0 ? 0 : -1;

                wsMethodName = "LayDanhSachKhuVuc";
                result = MovingServiceProxy.CallWebService(wsMovingURL, wsMovingName, wsMethodName, new object[] { });
                List<KhuVuc> khuVucs = WebServiceInvoker.ConvertType<List<KhuVuc>>(result);
                khuVucCBX.DataSource = khuVucs;
                khuVucCBX.DataValueField = "MaKhuVuc";
                khuVucCBX.DataTextField = "TenKhuVuc";
                khuVucCBX.DataBind();
                khuVucCBX.SelectedIndex = khuVucCBX.Items.Count > 0 ? 0 : -1;

                refreshThanhPhoCBX();
               
            }
            catch (Exception ex)
            {
                int a = 1;
            }
        }
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ProductID = int.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
        this.Cart.Remove(ProductID);
        this.FillShoppingCart();
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow ViewRow in GridView1.Rows)
        {
            int ProductID = int.Parse(ViewRow.Cells[0].Text);
            TextBox txtQuantity = (TextBox)ViewRow.Cells[3].FindControl("txtQuantity");
            int Quantity = int.Parse(txtQuantity.Text);

            this.Cart.Update(ProductID, Quantity);
        }
        this.FillShoppingCart();
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        this.Cart.Clear();
        this.FillShoppingCart();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("BonusProduct.aspx");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("Bonus.aspx");
    }
    protected void dsKhuVucCBX_SelectedIndexChanged(object sender, EventArgs e)
    {
        giaTienTXT.Text = hinhThucs[dsHinhThucCBX.SelectedIndex].GiaTien.ToString();
    }

    protected void btnCheckout_Click(object sender, EventArgs e)
    {
        string wsMethodName = "DangNhap"; 
        object obj = MovingServiceProxy.CallWebService(wsMovingURL, wsMovingName, wsMethodName, new object[] { "KH001", "moving001" });
        movingSID = (string)(obj);

        long cusID = -1;
        DataTable cus = (DataTable)Session["ThanhVien"];
        DataTable dt = (DataTable)Session["ShoppingCart"];

        cusID = int.Parse(cus.Rows[0][0].ToString());        

        bool datVanChuyenThanhCong = true;
        int maVC = -1;
        int tongSL = 0;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            // Đặt lệnh vận chuyển cho mỗi sản phẩm
            long prodID = long.Parse(dt.Rows[i][0].ToString());
            int prodQuantity = int.Parse(dt.Rows[i][3].ToString());
            tongSL += prodQuantity;

            DataAccess_Layer.Product prod = DataAccess_Layer.Product_DAC.get(prodID);

            wsMethodName = "DatLenhVanChuyen";
            int length = prod.ChieuDai.Value;
            int height = prod.ChieuDai.Value;
            int width = prod.ChieuRong.Value;
            int weigh = prod.KhoiLuong.Value;

            //obj = MovingServiceProxy.CallWebService(wsMovingURL, wsMovingName, wsMethodName, new object[] { movingSID, DateTime.Now.AddDays(10).ToString("dd/MM/yyyy"), khuVucCBX.SelectedValue, int.Parse(dsThanhPhoCBX.SelectedValue), dsHinhThucCBX.SelectedValue, "Mo ta hang vc", length, width, height, weigh });
            //List<String> kqvVanChuyen = (List<string>)(obj);
            //List<String> kqvVanChuyen  = new List<String>(movingWS.DatLenhVanChuyen(movingSID, DateTime.Now.AddDays(10).ToString("dd/MM/yyyy"), khuVucCBX.SelectedValue, int.Parse(dsThanhPhoCBX.SelectedValue), dsHinhThucCBX.SelectedValue, "Mo ta hang vc", chieudai, chieurong, chieucao, cannang));

            //if (kqvVanChuyen.Count == 1)
            //{
            //    datVanChuyenThanhCong = false;
            //}
            //else
            //{
            //    // lấy Mã vận chuyển của lần đặt lệnh thành công cuối cùng
            //    maVC = int.Parse(kqvVanChuyen[4].Split(':')[0]);
            //}
        }

        bool thanhToanThanhCong = false;
       string MaDonHang = DataAccess_Layer.LichSuMuaHang_DAC.layNewID();
       // string MaDonHang = "200";
        if (datVanChuyenThanhCong)
        {
            string UrlWebservice = "http://ecmoney10.tk/WebserviceMoiGioi/WebserviceMoiGioiMoney10.asmx";
            string ServiceName = "WebServiceMoiGioiMoney10";
            string MethodName = "GhiNhanDonHang";
            string MaVanChuyen = "VC01";
            int SoLuong = tongSL;
            decimal TongThanhToan = decimal.Parse(this.Cart.Total.ToString()); ;
            string TenChuTaiKhoan = "Trần Trịnh Khôi Nguyên";
            int TinhTrang = 1;
            string Email = "trantrinhkhoinguyen@gmail.com";
            string DienThoai = "0914123456";
            string DiaChi = "135 Nguyễn Văn Cừ";
            object[] arrOb = new object[9];
            arrOb[0] = MaDonHang;
            arrOb[1] = MaVanChuyen;
            arrOb[2] = SoLuong;
            arrOb[3] = TongThanhToan;
            arrOb[4] = TenChuTaiKhoan;
            arrOb[5] = TinhTrang;
            arrOb[6] = Email;
            arrOb[7] = DienThoai;
            arrOb[8] = DiaChi;
            object obResult = WSProxy_ForBanking.CallWebService(UrlWebservice, ServiceName, MethodName, arrOb);
            int kqDatThanhToan = (int)(obResult);

            if (kqDatThanhToan == 0)
            {
                //thanh toan thanh cong
                thanhToanThanhCong = true;
            }            
        }

        /////////////
        //Lich Su Mua Hang
        //////////////////
        if (thanhToanThanhCong)
        {
            DateTime time = DateTime.Now;
            string myStringVariable = string.Empty;
            myStringVariable = time.ToShortDateString();
            History hs = new History();
            hs.ID_Customer1 = int.Parse(cus.Rows[0]["ID"].ToString());
            hs.NgayLapHoaDon1 = myStringVariable;
            hs.TongTien1 = this.Cart.Total.ToString();
            int ID_LichSu = History_BUS.insert(hs);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                HistoryDetail hsd = new HistoryDetail();
                hsd.ID_LichSu1 = ID_LichSu;
                hsd.TenSanPham1 = dt.Rows[i]["ProductName"].ToString();
                hsd.SoLuong1 = dt.Rows[i]["Quantity"].ToString();
                hsd.GiaTien1 = dt.Rows[i]["UnitPrice"].ToString();
                hsd.ThanhTien1 = dt.Rows[i]["Amount"].ToString();
                History_BUS.insertDetail(hsd);
            }

            this.Cart.Clear();
            Response.Redirect("http://ecmoney10broker.tk/Transaction/ThanhToanTrucTuyen/" + MaDonHang);
        }

        Response.Redirect("ResultPayout.aspx?result=0");
    }
    void callBankingTEMP()
    {
        string UrlWebservice = "http://ecmoney10.tk/WebserviceMoiGioi/WebserviceMoiGioiMoney10.asmx";
        string ServiceName = "WebServiceMoiGioiMoney10";
        string MethodName = "GhiNhanDonHang";

        string MaDonHang = "99";
        string MaVanChuyen = "VC01";
        int SoLuong = 2;
        decimal TongThanhToan = 500000;
        string TenChuTaiKhoan = "Trần Trịnh Khôi Nguyên";
        int TinhTrang = 0;
        string Email = "trantrinhkhoinguyen@gmail.com";
        string DienThoai = "0914123456";
        string DiaChi = "135 Nguyễn Văn Cừ";
        object[] arrOb = new object[9];
        arrOb[0] = MaDonHang;
        arrOb[1] = MaVanChuyen;
        arrOb[2] = SoLuong;
        arrOb[3] = TongThanhToan;
        arrOb[4] = TenChuTaiKhoan;
        arrOb[5] = TinhTrang;
        arrOb[6] = Email;
        arrOb[7] = DienThoai;
        arrOb[8] = DiaChi;
        object obResult = WSProxy_ForBanking.CallWebService(UrlWebservice, ServiceName, MethodName, arrOb);
        int result = (int)obResult;
    }
    void FillShoppingCart()
    {
        GridView1.DataSource = this.Cart;
        GridView1.DataBind();

        ASP.masterpage_master master = (ASP.masterpage_master)this.Master;
        master.RefreshShoppingCartInfo();

        if (this.Cart.Count > 0)
        {
            GridView1.FooterRow.Cells[4].Text = String.Format("{0:0,0 VNĐ}", this.Cart.Total);
        }

        bool hasRow = Cart.Count > 0;
        btnUpdate.Enabled = hasRow;
        btnClear.Enabled = hasRow;
        btnCheckout.Enabled = (hasRow && Session["ThanhVien"] != null);
    }


    protected void khuVucCBX_SelectedIndexChanged(object sender, EventArgs e)
    {
        refreshThanhPhoCBX();
    }
    private void refreshThanhPhoCBX()
    {
        if (khuVucCBX.SelectedIndex != -1)
        {
            string wsMethodName = "LayDanhSachThanhPhoDenMotKhuVuc";
            object result = MovingServiceProxy.CallWebService(wsMovingURL, wsMovingName, wsMethodName, new object[] { khuVucCBX.SelectedValue });
            List<ThanhPho> thanhPhos = WebServiceInvoker.ConvertType<List<ThanhPho>>(result);
            dsThanhPhoCBX.DataSource = thanhPhos;
            dsThanhPhoCBX.DataValueField = "MaThanhPho";
            dsThanhPhoCBX.DataTextField = "TenThanhPho";
            dsThanhPhoCBX.DataBind();
        }
    }
    protected void btnXemLoTrinhTotNhat_Click(object sender, EventArgs e)
    {

    }
}
